import useDictStore from '/@/store/modules/dict'
import { dataSubDictionariesApi } from '/@/api/business/b-operation/data-dictionaries/data-sub-dictionaries-api'
import { dataDictionariesApi } from '/@/api/business/b-operation/data-dictionaries/data-dictionaries-api.js'
import { ref, toRefs } from 'vue'

/**
 * 获取字典数据
 */
export function useDict(...args) {
  const res = ref({})
  return (() => {
    args.forEach((dictType) => {
      res.value[dictType] = []
      const dicts = useDictStore().getDict(dictType)
      if (dicts) {
        res.value[dictType] = dicts
      } else {
        // dataDictionariesApi
        //   .findCode({ code: dictType })
        //   .then((findres) => {
        //     const dictId = findres.data.id
        //     dataSubDictionariesApi.queryPage({ dictId: dictId }).then((resp) => {
        //       res.value[dictType] = resp.data.map((p) => ({
        //         ...p,
        //         label: p.itemName,
        //         value: p.value,
        //         desc: p.itemName,
        //       }))
        //       useDictStore().setDict(dictType, res.value[dictType])
        //     })
        //   })
        //   .catch((err) => {
        //     // 获取字典数据失败
        //     console.log(`${dictType}---获取字典数据失败====>`, err.data)
        //   })
        dataSubDictionariesApi
          .listByCode({ code: dictType })
          .then((resp) => {
            res.value[dictType] = resp.data.map((p) => ({
              ...p,
              label: p.itemName,
              value: p.value,
              desc: p.itemName,
            }))
            useDictStore().setDict(dictType, res.value[dictType])
          })
          .catch((err) => {
            // 获取字典数据失败
            console.log(`${dictType}---获取字典数据失败====>`, err.data)
          })
      }
    })
    return toRefs(res.value)
  })()
}

export const getDictOptions = (dictType: string) => {
  return useDictStore().getDict(dictType)
}
export const getBoolDictOptions = (dictType: string) => {
  const dictOption: DictDataType[] = []
  const dictOptions: DictDataType[] = getDictOptions(dictType)
  dictOptions.forEach((dict: DictDataType) => {
    dictOption.push({
      ...dict,
      value: dict.value + '' === 'true',
    })
  })
  return dictOption
}

/**
 * 获取 dictType 对应的数据字典数组
 *
 * @param dictType 数据类型
 * @returns {*|Array} 数据字典数组
 */
export interface DictDataType {
  dictType: string
  label: string
  value: string | number | boolean
  cssClass: string
}
export const getIntDictOptions = (dictType: string) => {
  const dictOption: DictDataType[] = []
  const dictOptions: DictDataType[] = useDictStore().getDict(dictType)(dictType)
  dictOptions.forEach((dict: DictDataType) => {
    dictOption.push({
      ...dict,
      value: parseInt(dict.value + ''),
    })
  })

  return dictOption
}
